﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace Admin.Controls.Thumbnail
{
    partial class Thumbnail : System.Web.UI.UserControl
    {
        public int _ThumbHeight;
        public int _ThumbWidth;
        public string _OrigionalImage;
        public string _ThumbFolder;

        public string _ErrorImage;
        public int ThumbHeight
        {
            get { return _ThumbHeight; }
            set { _ThumbHeight = value; }
        }
        public int ThumbWidth
        {
            get { return _ThumbWidth; }
            set { _ThumbWidth = value; }
        }
        public string OrigionalImage
        {
            get { return _OrigionalImage; }
            set { _OrigionalImage = value; }
        }
        public string ThumbFolder
        {
            get { return _ThumbFolder; }
            set { _ThumbFolder = value; }
        }
        public string ErrorImage
        {
            get { return _ErrorImage; }
            set { _ErrorImage = value; }
        }

        private void DoThumb()
        {
            try
            {
                ImgThumb.ImageUrl = MakeThumb();
            }
            catch (Exception e)
            {
                ErrorImage = ErrorImage + "";
                if (string.IsNullOrEmpty(ErrorImage))
                {
                    ImgThumb.Visible = false;
                }
                else
                {
                    ImgThumb.ImageUrl = ErrorImage;
                }
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            DoThumb();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public string MakeThumb()
        {
            string OrgPath = Server.MapPath(OrigionalImage);
            string NewPath = Server.MapPath(ThumbFolder);

            System.Drawing.Image TempImage = System.Drawing.Image.FromFile(OrgPath);
            int ImageHeight = TempImage.Height;
            int ImageWidth = TempImage.Width;

            if (ThumbHeight == 0) ThumbHeight = ImageWidth / ThumbWidth * ImageHeight;
            if (ThumbWidth == 0) ThumbWidth = ImageHeight / ThumbHeight * ImageWidth;

            TempImage.Dispose();

            System.IO.FileInfo fi = new System.IO.FileInfo(OrgPath);
            string NewImageShort = "w" + ThumbWidth + "_h" + ThumbHeight + "_" + fi.Name;
            NewImageShort = NewImageShort.Replace(fi.Extension, ".jpg");

            string RootFolder = Server.MapPath("~");
            string Folders = OrgPath.Replace(RootFolder, "").Replace(fi.Name, "");
            if (Folders.Length > 0) Folders = Folders.TrimEnd('\\');
            string[] FolderList = Folders.Split('\\');

            string FolderPath = NewPath;
            for (int i = 0; i < FolderList.Length; i++)
            {
                FolderPath += "\\" + FolderList[i];
                if (!Directory.Exists(FolderPath)) Directory.CreateDirectory(FolderPath);
            }

            string NewImage = NewPath + "/" + Folders + "/" + NewImageShort;
            string NewImageWeb = ThumbFolder + "/" + Folders + "/" + NewImageShort;

            if (File.Exists(NewImage))
            {
                System.IO.FileInfo NewImagefi = new System.IO.FileInfo(OrgPath);
                DateTime OrigionalDateMod = fi.LastWriteTime;
                DateTime dateMod = NewImagefi.LastWriteTime;
                DateTime dateTod = DateTime.Now;
                if (dateMod.DayOfYear < OrigionalDateMod.DayOfYear | dateMod.Year < OrigionalDateMod.Year)
                {
                    NewImagefi.Delete();
                    ReSizeJpeg(OrgPath, ThumbHeight, ThumbWidth, ImageHeight, ImageWidth, NewImage);
                    return NewImageWeb;
                }
                else
                {
                    return NewImageWeb;
                }
            }
            else
            {
                ReSizeJpeg(OrgPath, ThumbHeight, ThumbWidth, ImageHeight, ImageWidth, NewImage);
                return NewImageWeb;
            }


        }

        public void ReSizeJpeg(string FilePath, int MaxHeight, int MaxWidth, int OHeight, int OWidth, string NewImage)
        {
            int PHeight = 0;
            int PWidth = 0;

            PHeight = OHeight;
            PWidth = OWidth;

            if (PHeight > MaxHeight)
            {
                PHeight = MaxHeight;
                PWidth = OWidth * PHeight / OHeight;
            }

            if (PWidth > MaxWidth)
            {
                PWidth = MaxWidth;
                PHeight = OHeight * PWidth / OWidth;
            }

            ReSizeJpegSave(PHeight, PWidth, FilePath, NewImage);

        }

        public void ReSizeJpegSave(int iHeight, int iWidth, string tempFile, string outputFile)
        {
            Bitmap originalImageSource = new Bitmap(tempFile);
            Bitmap resizedImage = new Bitmap(iWidth, iHeight);
            Graphics graphicsResized = Graphics.FromImage(resizedImage);
            EncoderParameters encParameters = new EncoderParameters(1);
            encParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 80L);

            graphicsResized.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            graphicsResized.DrawImage(originalImageSource, 0, 0, (resizedImage.Width + 1), (resizedImage.Height + 1));
            resizedImage.Save(outputFile, ReSizeJpegCodec(), encParameters);
            //resizedImage.Save(outputFile, encParameters, ReSizeJpegCodec());
            resizedImage.Dispose();
            graphicsResized.Dispose();
            originalImageSource.Dispose();
        }
        private ImageCodecInfo ReSizeJpegCodec()
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            foreach (ImageCodecInfo codec in codecs)
            {
                if ((codec.MimeType == "image/jpeg"))
                {
                    return codec;
                }
            }

            return null;
        }

    }
}